package com.wang.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

/**
 * TCP是一种可靠的传输层协议,它在通信两端各建立一个Socket,从而在C/S之间形成一条虚拟的通信链路,然后两端基于这条虚拟链路进行通信
 * (关于TCP协议的详细介绍可参考的博客TCP/IP入门(3) –传输层).Java对TCP提供了良好的封装,使用Socket对象来代表两端通信接口,
 * 并通过Socket产生的IO流来进行网络通信.
 */
	private static final ExecutorService executer = Executors.newFixedThreadPool(10);
	private static final int BUFFER_SIZE = 1024;
	
	public static void main(String[] args) throws Exception {
				
		ServerSocket server = new ServerSocket(8088);
		System.out.println("server 启动了! 监听端口8088");
		try{
			while(true){
				Socket client  = server.accept();
				System.out.println("检查到客户端,连接成功.");
				
				executer.submit(new ClientTask(client));			
			}			
		}catch(Exception e){
			System.out.println("服务端 跟客户端连接失败!");
			e.printStackTrace();
		}finally{
			server.close();
		}
		
	}
	
	private static class ClientTask implements Runnable{
		
		private Socket client;
		
		public ClientTask(Socket client) {
			this.client = client;
		}

		@Override
		public void run(){		
			
			try (InputStream in = client.getInputStream();
					OutputStream out = client.getOutputStream()) {
				String line;
				while (!(line = read(in)).isEmpty()) {
					System.out.println(line);
					out.write(String.format("echo: %s", line).getBytes());
					out.flush();
				}
				client.close();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					client.close();
				} catch (IOException e) {				
					e.printStackTrace();
				}
			}
			
		}
	}
	
	
	private static String read(InputStream in) throws Exception{		
		byte[] b = new byte[BUFFER_SIZE];
		int count = in.read(b);
		return new String(b,0,count);
	}
	
	
}
